package com.net.lnk.rpc.http.serialize.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.net.lnk.rpc.http.exception.RpcException;
import com.net.lnk.rpc.http.exception.RpcExceptionEnum;
import com.net.lnk.rpc.http.serialize.RpcFormater;
import com.net.lnk.rpc.http.serialize.RpcRequest;

/**
 * JSON 转换和解析工具类，使用的是Fastjson
 */
public class JsonRpcFormater implements RpcFormater {

	public static final RpcFormater formater = new JsonRpcFormater();

	public String formatRequest(Class<?> interfaceClass, String method, Object[] parameter) {
		RpcRequest request = new RpcRequest();
		request.setInterfaceClass(interfaceClass);
		request.setMethod(method);
		request.setParameter(parameter);
		return JSON.toJSONString(request, SerializerFeature.WriteClassName);
	}

	public String formateResponse(Object response) {

		return JSON.toJSONString(response, SerializerFeature.WriteClassName);
	}

	public RpcRequest parseRequest(String request) throws RpcException {
		try {
			return JSON.parseObject(request, RpcRequest.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RpcException(RpcExceptionEnum.DATA_PARSE_ERROR.getCode(),
					RpcExceptionEnum.DATA_PARSE_ERROR.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T parseResponse(String response) {

		return (T) JSON.parse(response);
	}
	
}
